package cn.stylefeng.guns.modular.mobile.controller;

import cn.janaker.paysdk.model.result.IUnifiedOrderResult;
import cn.janaker.paysdk.util.PayUtil;
import cn.janaker.paysdk.util.SysUtil;
import cn.stylefeng.guns.core.module.OrderStatus;
import cn.stylefeng.guns.modular.manager.entity.*;
import cn.stylefeng.guns.modular.manager.model.params.FlowCommissionManagementParam;
import cn.stylefeng.guns.modular.manager.model.params.FlowOrderGoodsParam;
import cn.stylefeng.guns.modular.manager.model.params.FlowOrderParam;
import cn.stylefeng.guns.modular.manager.model.result.FlowOrderGoodsResult;
import cn.stylefeng.guns.modular.manager.service.*;
import cn.stylefeng.guns.modular.mobile.base.MobileDouyingBaseController;
import cn.stylefeng.guns.modular.paytest.service.PayService;
import cn.stylefeng.guns.sys.modular.system.entity.Dept;
import cn.stylefeng.guns.sys.modular.system.entity.FlowDeptPhones;
import cn.stylefeng.guns.sys.modular.system.model.UploadResult;
import cn.stylefeng.guns.sys.modular.system.service.FileInfoService;
import cn.stylefeng.guns.utils.*;
import cn.stylefeng.guns.utils.douyin.DouyinHttpUtil;
import cn.stylefeng.guns.utils.douyin.DouyinPrePayRes;
import cn.stylefeng.guns.utils.map.BaiduMapUtil;
import cn.stylefeng.guns.utils.map.BaiduTransitionResult;
import cn.stylefeng.guns.utils.weixin.WeiXinUtil;
import cn.stylefeng.guns.utils.weixin.WxTemplateUtil;
import cn.stylefeng.roses.kernel.model.response.ResponseData;
import com.alipay.api.AlipayApiException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;

@Controller
@RequestMapping("/mobile/api/douyin")
public class MobileDouyinController extends MobileDouyingBaseController {
    @Autowired
    FlowProblemService flowProblemService;

    @Autowired
    FlowCouponService flowCouponService;
    @Autowired
    FlowServiceService flowServiceService;
    @Autowired
    FlowMemberLogService flowMemberLogService;
    @Autowired
    FlowOrderService flowOrderService;
    @Autowired
    FlowOrderLogService flowOrderLogService;
    @Autowired
    FlowOrderDisService flowOrderDisService;
    @Autowired
    FlowOrderGoodsService flowOrderGoodsService;
    @Autowired
    FlowServiceTypeService flowServiceTypeService;
    @Autowired
    FlowBillService flowBillService;
    @Autowired
    FlowPayInfoService flowPayInfoService;
    @Autowired
    FlowMemberCommentService flowMemberCommentService;

    @Autowired
    private FileInfoService fileInfoService;
    @Autowired
    FlowStoreCityService flowStoreCityService;
    @Autowired
    PayService payService;

    @Autowired
    private FlowZfbMemberService flowZfbMemberService;
    @Autowired
    private FlowBdMemberService flowBdMemberService;

    @Autowired
    private FlowDouyinMemberService flowDouyinMemberService;
    @Autowired
    private FlowCommissionManagementService flowCommissionManagementService;

    @RequestMapping("/memberInfo")
    @ResponseBody
    public ResponseData memberInfo(){
        return ResponseData.success(this.flowDouyinMember);
    }

    //提交问题反馈
    @RequestMapping("/uploadProblem")
    @ResponseBody
    public ResponseData uploadProblem(HttpServletRequest request){
        HttpBaseRequest baseRequest = new HttpBaseRequest(request);
        long type = baseRequest.getLong("type");
        String detail = baseRequest.getString("detail");
        if(type == -1){
            return ResponseData.error("请选择问题类型");
        }
        if(detail.equals("")){
            return ResponseData.error("请输入问题描述");
        }
        FlowProblem flowProblem = new FlowProblem();
        flowProblem.setCreateTime(new Date());
        flowProblem.setMemberPhone(this.flowDouyinMember.getAccount());
        flowProblem.setDyMemberId(this.flowDouyinMember.getMemberId());
        flowProblem.setProblemDetail(detail);
        flowProblem.setProblemType(type);
        flowProblem.setNote("");
        flowProblem.setStatus(0);
        flowProblem.setUpdateTime(new Date());
        boolean result = flowProblemService.save(flowProblem);
        if(result){
            return ResponseData.success("提交成功");
        }else {
            return ResponseData.error("提交失败");
        }
    }

    //获取用户的优惠卷
    @RequestMapping("/coupons")
    @ResponseBody
    public ResponseData coupons(HttpServletRequest request){
        HttpBaseRequest baseRequest = new HttpBaseRequest(request);
        int type = baseRequest.getInt("type");
        QueryWrapper<FlowCoupon> flowCouponQueryWrapper = new QueryWrapper<>();
        flowCouponQueryWrapper.eq("member_id",this.flowDouyinMember.getMemberId());
        flowCouponQueryWrapper.eq("is_get",1);
        if(type == 0){
            flowCouponQueryWrapper.eq("is_used",0);
        }else {
            flowCouponQueryWrapper.eq("is_used",1);
        }
        flowCouponQueryWrapper.eq("type",MEMBER_TYPE_DOUYIN);
        flowCouponQueryWrapper.orderByDesc("coupon_id");
        List<FlowCoupon> flowCoupons = flowCouponService.list(flowCouponQueryWrapper);
        List<FlowService> flowServices = flowServiceService.list();
        for (int i = 0;i<flowCoupons.size();i++){
            for (int j = 0;j<flowServices.size();j++){
                if(flowCoupons.get(i).getServiceType().longValue() == flowServices.get(j).getServiceId().longValue()){
                    flowCoupons.get(i).setServiceName(flowServices.get(j).getServiceName());
                }
            }
            int isOut = 0;
            if(flowCoupons.get(i).getOutDay().intValue() > 0){
                if(DateUtil.compareDate(flowCoupons.get(i).getEndTime(),new Date()) > 0){
                    isOut = 1;
                }
            }

            flowCoupons.get(i).setIsOut(isOut);
        }

        return ResponseData.success(flowCoupons);
    }

    //查询用户的地址
    @RequestMapping("/allLogs")
    @ResponseBody
    public ResponseData allLogs(HttpServletRequest request){
        HttpBaseRequest baseRequest = new HttpBaseRequest(request);
        int type = baseRequest.getInt("type");
        QueryWrapper<FlowMemberLog> flowMemberLogQueryWrapper = new QueryWrapper<>();
        flowMemberLogQueryWrapper.eq("type",type);
        flowMemberLogQueryWrapper.eq("dy_member_id",this.flowDouyinMember.getMemberId());
        flowMemberLogQueryWrapper.orderByDesc("member_log_id");
        List<FlowMemberLog> flowMemberLogs = flowMemberLogService.list(flowMemberLogQueryWrapper);

        return ResponseData.success(flowMemberLogs);
    }

    //添加或编辑用户地址
    @RequestMapping("/editLogs")
    @ResponseBody
    public ResponseData editLogs(HttpServletRequest request){
        HttpBaseRequest baseRequest = new HttpBaseRequest(request);
        long id = baseRequest.getLong("id");
        String address = baseRequest.getString("address");
        String country = baseRequest.getString("country");
        String province = baseRequest.getString("province");
        String city = baseRequest.getString("city");
        String elevator = baseRequest.getString("elevator");
        String poiName = baseRequest.getString("poiName");
        String latitude = baseRequest.getString("latitude");
        String longitude = baseRequest.getString("longitude");
        String detail = baseRequest.getString("detail");
        if(!address.equals("")){
            address = Escape.unescape(address);
        }
        if(!poiName.equals("")){
            poiName = Escape.unescape(poiName);
        }
        if(!elevator.equals("")){
            elevator = Escape.unescape(elevator);
        }
        if(!detail.equals("")){
            detail = Escape.unescape(detail);
        }
        //转换成百度坐标
        BaiduTransitionResult baiduTransitionResult = BaiduMapUtil.transition(longitude+","+latitude);
        String bdlatitude = "";
        String bdlongitude = "";
        if(baiduTransitionResult != null && baiduTransitionResult.getStatus() == 0){
            bdlongitude = baiduTransitionResult.getResult().get(0).getX();
            bdlatitude = baiduTransitionResult.getResult().get(0).getY();
        }
        long countryId = baseRequest.getLong("countryId");
        long provinceId = baseRequest.getLong("provinceId");
        long cityId = baseRequest.getLong("cityId");
        int type = baseRequest.getInt("type");
        int addressType = baseRequest.getInt("addressType");
        if(id == -1){
            FlowMemberLog flowMemberLog = new FlowMemberLog();
            flowMemberLog.setAddress(address);
            flowMemberLog.setAddressType(addressType);
            flowMemberLog.setCity(city);
            flowMemberLog.setCityId(cityId);
            flowMemberLog.setCountry(country);
            flowMemberLog.setCountryId(countryId);
            flowMemberLog.setProvince(province);
            flowMemberLog.setProvinceId(provinceId);
            flowMemberLog.setType(type);
            flowMemberLog.setCreateTime(new Date());
            flowMemberLog.setUpdateTime(new Date());
            flowMemberLog.setElevator(elevator);
            flowMemberLog.setPoiName(poiName);
            flowMemberLog.setLatitude(latitude);
            flowMemberLog.setLongitude(longitude);
            flowMemberLog.setDetail(detail);
            flowMemberLog.setBdLatitude(bdlatitude);
            flowMemberLog.setBdLongitude(bdlongitude);
            flowMemberLog.setDyMemberId(this.flowDouyinMember.getMemberId());
            boolean result = flowMemberLogService.save(flowMemberLog);
            if(result){
                return ResponseData.success(flowMemberLog.getMemberLogId());
            }else{
                return ResponseData.error("保存失败");
            }
        }else {
            QueryWrapper<FlowMemberLog> flowMemberLogQueryWrapper = new QueryWrapper<>();
            flowMemberLogQueryWrapper.eq("member_log_id",id);
            flowMemberLogQueryWrapper.eq("dy_member_id",this.flowDouyinMember.getMemberId());
            FlowMemberLog flowMemberLog = flowMemberLogService.getOne(flowMemberLogQueryWrapper);
            if(flowMemberLog == null){
                return ResponseData.error("不存在该数据");
            }
            flowMemberLog.setAddress(address);
            flowMemberLog.setAddressType(addressType);
            flowMemberLog.setCity(city);
            flowMemberLog.setCityId(cityId);
            flowMemberLog.setCountry(country);
            flowMemberLog.setCountryId(countryId);
            flowMemberLog.setProvince(province);
            flowMemberLog.setProvinceId(provinceId);
            flowMemberLog.setType(type);
            flowMemberLog.setUpdateTime(new Date());
            flowMemberLog.setElevator(elevator);
            flowMemberLog.setPoiName(poiName);
            flowMemberLog.setLatitude(latitude);
            flowMemberLog.setLongitude(longitude);
            flowMemberLog.setDetail(detail);
            flowMemberLog.setBdLatitude(bdlatitude);
            flowMemberLog.setBdLongitude(bdlongitude);
            boolean result = flowMemberLogService.updateById(flowMemberLog);
            if(result){
                return ResponseData.success(flowMemberLog.getMemberLogId());
            }else {
                return ResponseData.error("保存失败");
            }
        }
    }

    //删除用户地址
    @RequestMapping("/deleteLog")
    @ResponseBody
    public ResponseData deleteLog(HttpServletRequest request){
        HttpBaseRequest baseRequest = new HttpBaseRequest(request);
        long id = baseRequest.getLong("id");
        if(id == -1){
            return ResponseData.error("请选择删除数据");
        }
        QueryWrapper<FlowMemberLog> flowMemberLogQueryWrapper = new QueryWrapper<>();
        flowMemberLogQueryWrapper.eq("member_log_id",id);
        boolean result = flowMemberLogService.remove(flowMemberLogQueryWrapper);
        if(result){
            return ResponseData.success("删除成功");
        }else {
            return ResponseData.error("删除失败");
        }
    }

    //查询默认的地址
    @RequestMapping("/querylog")
    @ResponseBody
    public ResponseData querylog(HttpServletRequest request){
        HttpBaseRequest baseRequest = new HttpBaseRequest(request);
        int type = baseRequest.getInt("type",0);
        //0是国内。1是国外
        int addressType = baseRequest.getInt("addressType",0);
        //0是起始 1是终点
        QueryWrapper<FlowMemberLog> flowMemberLogQueryWrapper = new QueryWrapper<>();
        flowMemberLogQueryWrapper.eq("type",type);
        flowMemberLogQueryWrapper.eq("address_type",addressType);
        flowMemberLogQueryWrapper.orderByDesc("is_select");
        flowMemberLogQueryWrapper.eq("dy_member_id",this.flowDouyinMember.getMemberId());
        return ResponseData.success(flowMemberLogService.list(flowMemberLogQueryWrapper));
    }
    //设置
    @RequestMapping("/setLog")
    @ResponseBody
    public ResponseData setLog(HttpServletRequest request){
        HttpBaseRequest baseRequest = new HttpBaseRequest(request);
        long id = baseRequest.getLong("id");
        if(id == -1){
            return ResponseData.error("请选择删除数据");
        }
        QueryWrapper<FlowMemberLog> flowMemberLogQueryWrapper = new QueryWrapper<>();
        flowMemberLogQueryWrapper.eq("member_log_id",id);
        FlowMemberLog flowMemberLog = flowMemberLogService.getOne(flowMemberLogQueryWrapper);
        if(flowMemberLog == null){
            return ResponseData.error("不存在该数据");
        }
        if(flowMemberLog.getIsSelect().intValue() == 0){
            flowMemberLog.setIsSelect(1);
        }else{
            flowMemberLog.setIsSelect(0);
        }
        boolean result = flowMemberLogService.updateById(flowMemberLog);
        if(result){
            return ResponseData.success("");
        }else {
            return ResponseData.error("");
        }
    }

    //查询地址
    @RequestMapping("/log")
    @ResponseBody
    public ResponseData log(HttpServletRequest request){
        HttpBaseRequest baseRequest = new HttpBaseRequest(request);
        long id = baseRequest.getLong("id");
        if(id == -1){
            return ResponseData.error("请选择删除数据");
        }
        QueryWrapper<FlowMemberLog> flowMemberLogQueryWrapper = new QueryWrapper<>();
        flowMemberLogQueryWrapper.eq("member_log_id",id);
        FlowMemberLog flowMemberLog = flowMemberLogService.getOne(flowMemberLogQueryWrapper);

        return ResponseData.success(flowMemberLog);
    }

    @RequestMapping("/submitOrderTypeC")
    @ResponseBody
    public ResponseData submitOrderTypeC(HttpServletRequest request){
        HttpBaseRequest baseRequest = new HttpBaseRequest(request);
        long serviceType = baseRequest.getLong("id");
        if(serviceType == -1){
            return ResponseData.error("请选择类型");
        }
        long storeId = baseRequest.getLong("storeId");

        System.out.println("storeId1"+storeId);


        String begAddress = baseRequest.getString("begAddress");
        String endAddress = baseRequest.getString("endAddress");
        String begPoiName = baseRequest.getString("begPoiName");
        String endPoiName = baseRequest.getString("endPoiName");
        String begDetail = baseRequest.getString("begDetail");
        String endDetail = baseRequest.getString("endDetail");
        String begLocation = baseRequest.getString("begLocation");
        String endLocation = baseRequest.getString("endLocation");
        String begProvince = baseRequest.getString("begProvince");
        String begCity = baseRequest.getString("begCity");
        String endProvince = baseRequest.getString("endProvince");
        String endCity = baseRequest.getString("endCity");
        String begComAddress = baseRequest.getString("begComAddress");
        String endComAddress = baseRequest.getString("endComAddress");
        String begElevator = baseRequest.getString("begElevator");
        String endElevator = baseRequest.getString("endElevator");
        //格式化
        if(!begAddress.equals("")){
            begAddress = Escape.unescape(begAddress);
        }
        if(!endAddress.equals("")){
            endAddress = Escape.unescape(endAddress);
        }
        if(!begPoiName.equals("")){
            begPoiName = Escape.unescape(begPoiName);
        }
        if(!endPoiName.equals("")){
            endPoiName = Escape.unescape(endPoiName);
        }
        if(!begDetail.equals("")){
            begDetail = Escape.unescape(begDetail);
        }
        if(!endDetail.equals("")){
            endDetail = Escape.unescape(endDetail);
        }
        if(!begComAddress.equals("")){
            begComAddress = Escape.unescape(begComAddress);
        }
        if(!endComAddress.equals("")){
            endComAddress = Escape.unescape(endComAddress);
        }
        if(!begElevator.equals("")){
            begElevator = Escape.unescape(begElevator);
        }
        if(!endElevator.equals("")){
            endElevator = Escape.unescape(endElevator);
        }
        //
        if(begComAddress.equals("")){
            return ResponseData.error("请选择起点位置");
        }

        if(endComAddress.equals("")){
            return ResponseData.error("请选择终点位置");
        }

        //联系人信息
        String name = baseRequest.getString("name");

        String phone = baseRequest.getString("phone");

        String date = baseRequest.getString("date");

//        if(name.equals("")){
//            return ResponseData.error("请输入姓名");
//        }

        if(phone.equals("")){
            return ResponseData.error("请输入联系电话");
        }

        if(phone.length() != 11){
            return ResponseData.error("电话格式错误");
        }

        if(!CommonUtil.isMobileNO(phone)){
            return ResponseData.error("电话格式有误");
        }

        if(date.equals("")){
            return ResponseData.error("请输入搬运日期");
        }

        //创建该类型订单
        FlowOrder flowOrder = new FlowOrder();

        if(storeId != -1){
            System.out.println("storeId2"+storeId);

            //查询网点
            QueryWrapper<FlowStoreCity> flowStoreCityQueryWrapper = new QueryWrapper<>();
            flowStoreCityQueryWrapper.eq("store_city_id",storeId);
            FlowStoreCity flowStoreCity = flowStoreCityService.getOne(flowStoreCityQueryWrapper);
            if (flowStoreCity!=null){
                flowOrder.setStoreId(storeId);
                flowOrder.setStoreName(flowStoreCity.getStoreName());
            }

        }

        flowOrder.setDyMemberId(this.flowDouyinMember.getMemberId());
        flowOrder.setBegAddress(begComAddress);
        flowOrder.setEndAddress(endComAddress);
        flowOrder.setBegLocation(begLocation);
        flowOrder.setEndLocation(endLocation);
        flowOrder.setOrderType(serviceType);
        flowOrder.setName(name);
        flowOrder.setPhone(phone);
        flowOrder.setUseDate(date);
        flowOrder.setUpdateTime(new Date());
        flowOrder.setCreateTime(new Date());
        flowOrder.setServiceCity(begCity);
        //订单状态
        flowOrder.setOrderCode(CommonUtil.getRanDomStringId());
        flowOrder.setOrderStatus(OrderStatus.OrderWaitConfirm);
        flowOrder.setIsRefund(OrderStatus.NoRefund);
        flowOrder.setPayStatus(OrderStatus.NoPay);
        flowOrder.setOrderFrom(OrderStatus.fromDY);
        //
        boolean result = flowOrderService.save(flowOrder);
        if(!result){
            return ResponseData.error("预约失败");
        }
        FlowOrderLog flowOrderLog = new FlowOrderLog();
        flowOrderLog.setBegAddress(begAddress);
        flowOrderLog.setBegCity(begCity);
        flowOrderLog.setBegProvince(begProvince);
        flowOrderLog.setBegComAddress(begComAddress);
        flowOrderLog.setBegDetail(begDetail);
        flowOrderLog.setBegElevator(begElevator);
        flowOrderLog.setBegLocation(begLocation);
        flowOrderLog.setBegPoiName(begPoiName);

        flowOrderLog.setEndAddress(endAddress);
        flowOrderLog.setEndCity(endCity);
        flowOrderLog.setEndComAddress(endComAddress);
        flowOrderLog.setEndElevator(endElevator);
        flowOrderLog.setEndDetail(endDetail);
        flowOrderLog.setEndLocation(endLocation);
        flowOrderLog.setEndProvince(endProvince);
        flowOrderLog.setEndPoiName(endPoiName);

        flowOrderLog.setOrderId(flowOrder.getOrderId());

        flowOrderLog.setCreateTime(new Date());
        flowOrderLog.setUpdateTime(new Date());

        flowOrderLogService.save(flowOrderLog);
        this.sendMsg(flowOrder);
        return ResponseData.success(flowOrder.getOrderId());
    }

    @RequestMapping("/submitOrderTypeD")
    @ResponseBody
    public ResponseData submitOrderTypeD(HttpServletRequest request){
        HttpBaseRequest baseRequest = new HttpBaseRequest(request);
        long serviceType = baseRequest.getLong("id");
        if(serviceType == -1){
            return ResponseData.error("请选择类型");
        }
        String begAddress = baseRequest.getString("begAddress");
        String endAddress = baseRequest.getString("endAddress");
        String begPoiName = baseRequest.getString("begPoiName");
        String endPoiName = baseRequest.getString("endPoiName");
        String begDetail = baseRequest.getString("begDetail");
        String endDetail = baseRequest.getString("endDetail");
        String begLocation = baseRequest.getString("begLocation");
        String endLocation = baseRequest.getString("endLocation");
        String begProvince = baseRequest.getString("begProvince");
        String begCity = baseRequest.getString("begCity");
        String endProvince = baseRequest.getString("endProvince");
        String endCity = baseRequest.getString("endCity");
        String begComAddress = baseRequest.getString("begComAddress");
        String endComAddress = baseRequest.getString("endComAddress");
        String begElevator = baseRequest.getString("begElevator");
        String endElevator = baseRequest.getString("endElevator");
        //格式化
        if(!begAddress.equals("")){
            begAddress = Escape.unescape(begAddress);
        }
        if(!endAddress.equals("")){
            endAddress = Escape.unescape(endAddress);
        }
        if(!begPoiName.equals("")){
            begPoiName = Escape.unescape(begPoiName);
        }
        if(!endPoiName.equals("")){
            endPoiName = Escape.unescape(endPoiName);
        }
        if(!begDetail.equals("")){
            begDetail = Escape.unescape(begDetail);
        }
        if(!endDetail.equals("")){
            endDetail = Escape.unescape(endDetail);
        }
        if(!begComAddress.equals("")){
            begComAddress = Escape.unescape(begComAddress);
        }
        if(!endComAddress.equals("")){
            endComAddress = Escape.unescape(endComAddress);
        }
        if(!begElevator.equals("")){
            begElevator = Escape.unescape(begElevator);
        }
        if(!endElevator.equals("")){
            endElevator = Escape.unescape(endElevator);
        }
        //
        if(begComAddress.equals("")){
            return ResponseData.error("请选择起点位置");
        }

        if(endComAddress.equals("")){
            return ResponseData.error("请选择终点位置");
        }

        //联系人信息
        String name = baseRequest.getString("name");

        String phone = baseRequest.getString("phone");

//        if(name.equals("")){
//            return ResponseData.error("请输入姓名");
//        }

        if(phone.equals("")){
            return ResponseData.error("请输入联系电话");
        }

        if(phone.length() != 11){
            return ResponseData.error("电话格式错误");
        }

        if(!CommonUtil.isMobileNO(phone)){
            return ResponseData.error("电话格式有误");
        }

        //创建该类型订单
        FlowOrder flowOrder = new FlowOrder();
        flowOrder.setDyMemberId(this.flowDouyinMember.getMemberId());
        flowOrder.setBegAddress(begComAddress);
        flowOrder.setEndAddress(endComAddress);
        flowOrder.setBegLocation(begLocation);
        flowOrder.setEndLocation(endLocation);
        flowOrder.setOrderType(serviceType);
        flowOrder.setName(name);
        flowOrder.setPhone(phone);
        flowOrder.setUseDate("");
        flowOrder.setUpdateTime(new Date());
        flowOrder.setCreateTime(new Date());
        flowOrder.setServiceCity(begCity);
        //订单状态
        flowOrder.setOrderCode(CommonUtil.getRanDomStringId());
        flowOrder.setOrderStatus(OrderStatus.OrderWaitConfirm);
        flowOrder.setIsRefund(OrderStatus.NoRefund);
        flowOrder.setPayStatus(OrderStatus.NoPay);
        flowOrder.setOrderFrom(OrderStatus.fromDY);
        //
        boolean result = flowOrderService.save(flowOrder);
        if(!result){
            return ResponseData.error("预约失败");
        }
        FlowOrderLog flowOrderLog = new FlowOrderLog();
        flowOrderLog.setBegAddress(begAddress);
        flowOrderLog.setBegCity(begCity);
        flowOrderLog.setBegProvince(begProvince);
        flowOrderLog.setBegComAddress(begComAddress);
        flowOrderLog.setBegDetail(begDetail);
        flowOrderLog.setBegElevator(begElevator);
        flowOrderLog.setBegLocation(begLocation);
        flowOrderLog.setBegPoiName(begPoiName);

        flowOrderLog.setEndAddress(endAddress);
        flowOrderLog.setEndCity(endCity);
        flowOrderLog.setEndComAddress(endComAddress);
        flowOrderLog.setEndElevator(endElevator);
        flowOrderLog.setEndDetail(endDetail);
        flowOrderLog.setEndLocation(endLocation);
        flowOrderLog.setEndProvince(endProvince);
        flowOrderLog.setEndPoiName(endPoiName);

        flowOrderLog.setOrderId(flowOrder.getOrderId());

        flowOrderLog.setCreateTime(new Date());
        flowOrderLog.setUpdateTime(new Date());

        flowOrderLogService.save(flowOrderLog);
        this.sendMsg(flowOrder);
        return ResponseData.success(flowOrder.getOrderId());
    }

    @RequestMapping("/submitOrderTypeE")
    @ResponseBody
    public ResponseData submitOrderTypeE(HttpServletRequest request){
        HttpBaseRequest baseRequest = new HttpBaseRequest(request);
        long serviceType = baseRequest.getLong("id");
        if(serviceType == -1){
            return ResponseData.error("请选择类型");
        }
        String begAddress = baseRequest.getString("begAddress");
        String begPoiName = baseRequest.getString("begPoiName");
        String begDetail = baseRequest.getString("begDetail");
        String begLocation = baseRequest.getString("begLocation");
        String begProvince = baseRequest.getString("begProvince");
        String begCity = baseRequest.getString("begCity");
        String begComAddress = baseRequest.getString("begComAddress");
        String begElevator = baseRequest.getString("begElevator");
        //联系人信息
        String name = baseRequest.getString("name");

        String phone = baseRequest.getString("phone");

//        if(name.equals("")){
//            return ResponseData.error("请输入姓名");
//        }

        if(phone.equals("")){
            return ResponseData.error("请输入联系电话");
        }

        if(phone.length() != 11){
            return ResponseData.error("电话格式错误");
        }

        if(!CommonUtil.isMobileNO(phone)){
            return ResponseData.error("电话格式有误");
        }

        //格式化
        if(!begAddress.equals("")){
            begAddress = Escape.unescape(begAddress);
        }
        if(!begPoiName.equals("")){
            begPoiName = Escape.unescape(begPoiName);
        }
        if(!begDetail.equals("")){
            begDetail = Escape.unescape(begDetail);
        }
        if(!begComAddress.equals("")){
            begComAddress = Escape.unescape(begComAddress);
        }
        if(!begElevator.equals("")){
            begElevator = Escape.unescape(begElevator);
        }
        //
        if(begComAddress.equals("")){
            return ResponseData.error("请选择起点位置");
        }

        //创建该类型订单
        FlowOrder flowOrder = new FlowOrder();
        flowOrder.setDyMemberId(this.flowDouyinMember.getMemberId());
        flowOrder.setBegAddress(begAddress);
        flowOrder.setServiceCity(begCity);
        flowOrder.setBegAddress(begComAddress);
        flowOrder.setBegElevator(begElevator);
        flowOrder.setBegLocation(begLocation);
        flowOrder.setOrderType(serviceType);
        flowOrder.setName(name);
        flowOrder.setPhone(phone);
        flowOrder.setUseDate("");
        flowOrder.setUpdateTime(new Date());
        flowOrder.setCreateTime(new Date());

        //订单状态
        flowOrder.setOrderCode(CommonUtil.getRanDomStringId());
        flowOrder.setOrderStatus(OrderStatus.OrderWaitConfirm);
        flowOrder.setIsRefund(OrderStatus.NoRefund);
        flowOrder.setPayStatus(OrderStatus.NoPay);
        flowOrder.setOrderFrom(OrderStatus.fromDY);
        //
        boolean result = flowOrderService.save(flowOrder);
        if(!result){
            return ResponseData.error("预约失败");
        }
        FlowOrderLog flowOrderLog = new FlowOrderLog();
        flowOrderLog.setBegAddress(begAddress);
        flowOrderLog.setBegCity(begCity);
        flowOrderLog.setBegProvince(begProvince);
        flowOrderLog.setBegComAddress(begComAddress);
        flowOrderLog.setBegDetail(begDetail);
        flowOrderLog.setBegElevator(begElevator);
        flowOrderLog.setBegLocation(begLocation);
        flowOrderLog.setBegPoiName(begPoiName);

        flowOrderLog.setEndAddress(begAddress);
        flowOrderLog.setEndCity(begCity);
        flowOrderLog.setEndComAddress("");
        flowOrderLog.setEndElevator("");
        flowOrderLog.setEndDetail("");
        flowOrderLog.setEndLocation("");
        flowOrderLog.setEndProvince("");
        flowOrderLog.setEndPoiName("");

        flowOrderLog.setOrderId(flowOrder.getOrderId());

        flowOrderLog.setCreateTime(new Date());
        flowOrderLog.setUpdateTime(new Date());

        flowOrderLogService.save(flowOrderLog);
        this.sendMsg(flowOrder);
        return ResponseData.success(flowOrder.getOrderId());
    }
//
//    //预下单
//    @RequestMapping("/preOrder")
//    @ResponseBody
//    public ResponseData preOrder(){
//
//    }
//
//    //创建同城，或者跨市订单
//    @RequestMapping("/createOrder")
//    @ResponseBody
//    public ResponseData createOrder(){
//
//    }


    //提交发票
    //判断该订单号是否存在
    @RequestMapping("/orderDetail")
    @ResponseBody
    public ResponseData orderDetail(HttpServletRequest request){
        HttpBaseRequest baseRequest = new HttpBaseRequest(request);
        long orderId = baseRequest.getLong("orderId");
        if(orderId == -1){
            return ResponseData.error("请选择订单");
        }
        //查询订单
        QueryWrapper<FlowOrder> flowOrderQueryWrapper = new QueryWrapper<>();
        flowOrderQueryWrapper.eq("order_id",orderId);
        flowOrderQueryWrapper.last("limit 1");
        FlowOrder flowOrder = flowOrderService.getOne(flowOrderQueryWrapper);
        if(flowOrder == null){
            return ResponseData.error("不存在该订单");
        }

        //查询订单的具体地理位置
        QueryWrapper<FlowOrderLog> flowOrderLogQueryWrapper = new QueryWrapper<>();
        flowOrderLogQueryWrapper.eq("order_id",flowOrder.getOrderId());
        flowOrderLogQueryWrapper.last("limit 1");
        FlowOrderLog flowOrderLog = flowOrderLogService.getOne(flowOrderLogQueryWrapper);
        if(flowOrderLog != null){
            flowOrder.setBegAddress(flowOrderLog.getBegComAddress() + " " + flowOrderLog.getBegDetail());
            flowOrder.setEndAddress(flowOrderLog.getEndComAddress() + " " + flowOrderLog.getEndDetail());
            flowOrder.setBegElevator(flowOrderLog.getBegElevator());
            flowOrder.setEndElevator(flowOrderLog.getEndElevator());
            flowOrder.setBegDetail(flowOrderLog.getBegDetail());
            flowOrder.setEndDetail(flowOrderLog.getEndDetail());
        }

        //查询订单的服务类型
        QueryWrapper<FlowService> flowServiceQueryWrapper = new QueryWrapper<>();
        flowServiceQueryWrapper.eq("service_id",flowOrder.getOrderType());
        flowServiceQueryWrapper.last("limit 1");
        FlowService flowService = flowServiceService.getOne(flowServiceQueryWrapper);
        if(flowService != null){
            flowOrder.setOrderTypeName(flowService.getServiceName());
        }

        //查询同城订单的服务类型
        if(flowOrder.getOrderType().longValue() == 1){
            QueryWrapper<FlowServiceType> flowServiceTypeQueryWrapper = new QueryWrapper<>();
            flowServiceTypeQueryWrapper.eq("service_type_id",flowOrder.getServiceType());
            flowServiceTypeQueryWrapper.last("limit 1");
            FlowServiceType flowServiceType = flowServiceTypeService.getOne(flowServiceTypeQueryWrapper);
            if(flowServiceType != null){
                flowOrder.setServiceName(flowServiceType.getTypeName());
            }
        }

        //查询订单的物品
        FlowOrderGoodsParam flowOrderGoodsParam = new FlowOrderGoodsParam();
        flowOrderGoodsParam.setOrderId(flowOrder.getOrderId());
        List<FlowOrderGoodsResult> flowOrderGoods = flowOrderGoodsService.selectOrderDisList(flowOrderGoodsParam);
        flowOrder.setFlowOrderGoods(flowOrderGoods);
        //查询订单使用的优惠卷
        QueryWrapper<FlowOrderDis> flowOrderDisQueryWrapper = new QueryWrapper<>();
        flowOrderDisQueryWrapper.eq("order_id",flowOrder.getOrderId());
        flowOrderDisQueryWrapper.last("limit 1");
        FlowOrderDis flowOrderDis = flowOrderDisService.getOne(flowOrderDisQueryWrapper);
        flowOrder.setFlowOrderDis(flowOrderDis);

        return ResponseData.success(flowOrder);
    }

    @RequestMapping("/orderBill")
    @ResponseBody
    public ResponseData orderBill(HttpServletRequest request){
        HttpBaseRequest baseRequest = new HttpBaseRequest(request);
        String orderCode = baseRequest.getString("orderCode");
        if(orderCode.equals("")){
            return ResponseData.error("请输入订单号");
        }
        //查询订单
        QueryWrapper<FlowOrder> flowOrderQueryWrapper = new QueryWrapper<>();
        flowOrderQueryWrapper.eq("order_code",orderCode);
        flowOrderQueryWrapper.last("limit 1");
        FlowOrder flowOrder = flowOrderService.getOne(flowOrderQueryWrapper);
        if(flowOrder == null){
            return ResponseData.error("不存在该订单");
        }
        if(flowOrder.getOrderStatus().intValue() != OrderStatus.OrderServiceSuccess && flowOrder.getOrderStatus().intValue() != OrderStatus.OrderCompletion){
            return ResponseData.error("订单未完成，不能申请发票");
        }
        //查询是否已经申请
        QueryWrapper<FlowBill> flowBillQueryWrapper = new QueryWrapper<>();
        flowBillQueryWrapper.eq("order_code",orderCode);
        flowBillQueryWrapper.last("limit 1");
        FlowBill flowBill = flowBillService.getOne(flowBillQueryWrapper);
        if(flowBill != null){
            return ResponseData.error("该订单已申请发票");
        }
        Map<String,Object> res = new HashMap<>();
        res.put("orderId",flowOrder.getOrderId());
        res.put("moneys",flowOrder.getAllPayMoneys());
        return ResponseData.success(res);
    }

    @RequestMapping("/confirmBill")
    @ResponseBody
    public ResponseData confirmBill(HttpServletRequest request){
        HttpBaseRequest baseRequest = new HttpBaseRequest(request);
        int titleType = baseRequest.getInt("titleType");
        long orderId = baseRequest.getLong("orderId");
        String title = baseRequest.getString("title");
        String idCode = baseRequest.getString("idCode");
        String note = baseRequest.getString("note");
        int billType = baseRequest.getInt("billType");
        String contact = baseRequest.getString("contact");
        String phone = baseRequest.getString("phone");
        String address = baseRequest.getString("address");
        String email = baseRequest.getString("email");
        QueryWrapper<FlowOrder> flowOrderQueryWrapper = new QueryWrapper<>();
        flowOrderQueryWrapper.eq("order_id",orderId);
        flowOrderQueryWrapper.last("limit 1");
        FlowOrder flowOrder = flowOrderService.getOne(flowOrderQueryWrapper);
        if(flowOrder == null){
            return ResponseData.error("不存在该订单");
        }
        if(flowOrder.getOrderStatus().intValue() != OrderStatus.OrderServiceSuccess && flowOrder.getOrderStatus().intValue() != OrderStatus.OrderCompletion){
            return ResponseData.error("订单未完成，不能申请发票");
        }
        FlowBill flowBill = new FlowBill();
        flowBill.setAddress(address);
        flowBill.setBillType(billType);
        flowBill.setContact(contact);
        flowBill.setCreateTime(new Date());
        flowBill.setEmail(email);
        flowBill.setIdCode(idCode);
        flowBill.setMoneys(flowOrder.getAllPayMoneys());
        flowBill.setNote(note);
        flowBill.setOrderCode(flowOrder.getOrderCode());
        flowBill.setOrderId(orderId);
        flowBill.setPhone(phone);
        flowBill.setTitle(title);
        flowBill.setTitleType(titleType);
        flowBill.setUpdateTime(new Date());
        flowBill.setStoreId(flowOrder.getStoreId());
        boolean result = flowBillService.save(flowBill);
        if(result){
            return ResponseData.success("保存成功");
        }else {
            return ResponseData.error("保存失败");
        }
    }

    @RequestMapping("/canuseCoupon")
    @ResponseBody
    public ResponseData canuseCoupon(HttpServletRequest request){
        HttpBaseRequest baseRequest = new HttpBaseRequest(request);
        long id = baseRequest.getLong("id");
        if(id == -1){
            return ResponseData.error("请选择物流类型");
        }
        double price = baseRequest.getDouble("price",0);
        //查询红包
        QueryWrapper<FlowCoupon> flowCouponQueryWrapper = new QueryWrapper<>();
        flowCouponQueryWrapper.eq("member_id",this.flowDouyinMember.getMemberId());
        flowCouponQueryWrapper.le("onprice",price);
        flowCouponQueryWrapper.eq("is_get",1);
        flowCouponQueryWrapper.eq("is_used",0);
        flowCouponQueryWrapper.eq("type",MEMBER_TYPE_DOUYIN);
        flowCouponQueryWrapper.apply("(service_type = -1 or service_type = "+id+")");
        flowCouponQueryWrapper.apply("(out_day <= 0 or DATE_SUB(CURDATE(), INTERVAL out_day DAY) <= date(get_time))");
        flowCouponQueryWrapper.orderByAsc("moneys");
        List<FlowCoupon> flowCoupons = flowCouponService.list(flowCouponQueryWrapper);
        List<FlowService> flowServices = flowServiceService.list();
        for (int i = 0;i<flowCoupons.size();i++){
            for (int j = 0;j<flowServices.size();j++){
                if(flowCoupons.get(i).getServiceType().longValue() == flowServices.get(j).getServiceId().longValue()){
                    flowCoupons.get(i).setServiceName(flowServices.get(j).getServiceName());
                }
            }
        }
        return ResponseData.success(flowCoupons);
    }

    //订单列表
    @RequestMapping("/orderList")
    @ResponseBody
    public ResponseData orderList(HttpServletRequest request){
        HttpBaseRequest baseRequest = new HttpBaseRequest(request);
        int pagesize = baseRequest.getInt("pagesize",10);
        int cpage = baseRequest.getInt("cpage",1);
        long type = baseRequest.getLong("type");

        QueryWrapper<FlowOrder> flowOrderQueryWrapper = new QueryWrapper<>();
        flowOrderQueryWrapper.eq("dy_member_id",this.flowDouyinMember.getMemberId());
        if(type == 0){
            flowOrderQueryWrapper.apply("(order_status != "+OrderStatus.OrderCansel+" and order_status != "+OrderStatus.OrderServiceSuccess+" and order_status != "+OrderStatus.OrderCompletion+")");
        }else if(type == 1){
            flowOrderQueryWrapper.apply("(order_status = "+OrderStatus.OrderServiceSuccess+" or order_status = "+OrderStatus.OrderCompletion+")");
        }else {
            flowOrderQueryWrapper.eq("order_status",OrderStatus.OrderCansel);
        }

        flowOrderQueryWrapper.orderByDesc("create_time");

        IPage page = new Page<FlowOrder>(cpage,pagesize);
        page = flowOrderService.getBaseMapper().selectPage(page,flowOrderQueryWrapper);
        List<FlowOrder> flowOrders = page.getRecords();
        if(flowOrders.size() != 0){
            List<Long> ids = new ArrayList<>();
            for (int i = 0;i < flowOrders.size();i++){
                ids.add(flowOrders.get(i).getOrderType());
                flowOrders.get(i).setOrderStatusStr(flowOrderService.orderStatus(flowOrders.get(i).getOrderStatus()));
            }
            //查询订单的服务类型
            QueryWrapper<FlowService> flowServiceQueryWrapper = new QueryWrapper<>();
            flowServiceQueryWrapper.in("service_id",ids);
            List<FlowService> flowService = flowServiceService.list(flowServiceQueryWrapper);
            for (int i = 0;i < flowOrders.size();i++){
                for (int j = 0;j<flowService.size();j++){
                    if(flowOrders.get(i).getOrderType().longValue() == flowService.get(j).getServiceId().longValue()){
                        flowOrders.get(i).setOrderTypeName(flowService.get(j).getServiceName());
                        break;
                    }
                }
            }
        }

        return ResponseData.success(flowOrders);
    }

    //使用优惠卷
    @RequestMapping("/useCoupon")
    @ResponseBody
    public ResponseData useCoupon(HttpServletRequest request){
        HttpBaseRequest baseRequest = new HttpBaseRequest(request);
        long id = baseRequest.getLong("id");
        if(id == -1){
            return ResponseData.error("请选择物流类型");
        }
        double price = baseRequest.getDouble("price",0);
        //查询红包
        QueryWrapper<FlowCoupon> flowCouponQueryWrapper = new QueryWrapper<>();
        flowCouponQueryWrapper.eq("member_id",this.flowDouyinMember.getMemberId());
        flowCouponQueryWrapper.le("onprice",price);
        flowCouponQueryWrapper.eq("is_get",1);
        flowCouponQueryWrapper.eq("is_used",0);
        flowCouponQueryWrapper.eq("type",MEMBER_TYPE_DOUYIN);
        flowCouponQueryWrapper.apply("(service_type = -1 or service_type = "+id+")");
        flowCouponQueryWrapper.apply("(out_day <= 0 or DATE_SUB(CURDATE(), INTERVAL out_day DAY) <= date(get_time))");
        flowCouponQueryWrapper.orderByAsc("moneys");
        flowCouponQueryWrapper.last("limit 1");
        FlowCoupon flowCoupon = flowCouponService.getOne(flowCouponQueryWrapper);
        if(flowCoupon == null){
            return ResponseData.error("");
        }else {
            return ResponseData.success(flowCoupon);
        }
    }

    //提交订单
    @RequestMapping("/submitOrder")
    @ResponseBody
    public ResponseData submitOrder(HttpServletRequest request){
        HttpBaseRequest baseRequest = new HttpBaseRequest(request);
        String allPay=baseRequest.getString("allPay");
        long id = baseRequest.getLong("id");
        if(id == -1){
            return ResponseData.error("请选择类型");
        }
        long serviceType = baseRequest.getLong("serviceType");

        if(serviceType == -1){
            return ResponseData.error("请选择类型");
        }

        long storeId = baseRequest.getLong("storeId");
        if(storeId == -1){
            return ResponseData.error("该地区服务未开通~");
        }
        //查询网点
        QueryWrapper<FlowStoreCity> flowStoreCityQueryWrapper = new QueryWrapper<>();
        flowStoreCityQueryWrapper.eq("store_city_id",storeId);
        FlowStoreCity flowStoreCity = flowStoreCityService.getOne(flowStoreCityQueryWrapper);
        if(flowStoreCity == null){
            return ResponseData.error("不存在该网点");
        }
        String notes = baseRequest.getString("notes");
        long couponId = baseRequest.getLong("couponId");
        double distance = baseRequest.getDouble("distance",0);
        double distancePrice = baseRequest.getDouble("distancePrice",0);
        String distanceNotes = baseRequest.getString("distanceNotes");
        if(!distanceNotes.equals("")){
            distanceNotes = Escape.unescape(distanceNotes);
        }
        if(!notes.equals("")){
            notes = Escape.unescape(notes);
        }
        String cGoods = baseRequest.getString("cGoods");
        //物品费用
        double basePrice = baseRequest.getDouble("basePrice",0);

        String begAddress = baseRequest.getString("begAddress");
        String endAddress = baseRequest.getString("endAddress");
        String begPoiName = baseRequest.getString("begPoiName");
        String endPoiName = baseRequest.getString("endPoiName");
        String begDetail = baseRequest.getString("begDetail");
        String endDetail = baseRequest.getString("endDetail");
        String begLocation = baseRequest.getString("begLocation");
        String endLocation = baseRequest.getString("endLocation");
        String begProvince = baseRequest.getString("begProvince");
        String begCity = baseRequest.getString("begCity");
        String endProvince = baseRequest.getString("endProvince");
        String endCity = baseRequest.getString("endCity");
        String begComAddress = baseRequest.getString("begComAddress");
        String endComAddress = baseRequest.getString("endComAddress");
        String begElevator = baseRequest.getString("begElevator");
        String endElevator = baseRequest.getString("endElevator");
        String superUserId = baseRequest.getString("superUserId");
        double begElevatorPrice = baseRequest.getDouble("begElevatorPrice",0);
        double endElevatorPrice = baseRequest.getDouble("endElevatorPrice",0);

        //格式化
        if(!begAddress.equals("")){
            begAddress = Escape.unescape(begAddress);
        }
        if(!endAddress.equals("")){
            endAddress = Escape.unescape(endAddress);
        }
        if(!begPoiName.equals("")){
            begPoiName = Escape.unescape(begPoiName);
        }
        if(!endPoiName.equals("")){
            endPoiName = Escape.unescape(endPoiName);
        }
        if(!begDetail.equals("")){
            begDetail = Escape.unescape(begDetail);
        }
        if(!endDetail.equals("")){
            endDetail = Escape.unescape(endDetail);
        }
        if(!begComAddress.equals("")){
            begComAddress = Escape.unescape(begComAddress);
        }
        if(!endComAddress.equals("")){
            endComAddress = Escape.unescape(endComAddress);
        }
        if(!begElevator.equals("")){
            begElevator = Escape.unescape(begElevator);
        }
        if(!endElevator.equals("")){
            endElevator = Escape.unescape(endElevator);
        }
        //

        if(begComAddress.equals("")){
            return ResponseData.error("请选择起点位置");
        }

        if(endComAddress.equals("")){
            return ResponseData.error("请选择终点位置");
        }

        if(!cGoods.equals("")){
            cGoods = Escape.unescape(cGoods);
        }

        //联系人信息
        String name = baseRequest.getString("name");

        String phone = baseRequest.getString("phone");

        String date = baseRequest.getString("date");

//        if(name.equals("")){
//            return ResponseData.error("请输入姓名");
//        }

        if(phone.equals("")){
            return ResponseData.error("请输入联系电话");
        }

        if(phone.length() != 11){
            return ResponseData.error("电话格式错误");
        }

        if(!CommonUtil.isMobileNO(phone)){
            return ResponseData.error("电话格式有误");
        }

        if(date.equals("")){
            return ResponseData.error("请输入搬运日期");
        }

        //计算订单费用
        double goodsPrice = 0;
        List<FlowOrderGoods> flowOrderGoods = new ArrayList<>();
        if(!cGoods.equals("")){
            String[]arr = cGoods.split(",");
            //id,count,price,name
            for (int i= 0;i<arr.length;i++){
                String a[] = arr[i].split("#");
                if(a.length != 4){
                    continue;
                }
                Long gid = Long.parseLong(a[0]);
                int count = Integer.parseInt(a[1]);
                double price = Double.parseDouble(a[2]);
                FlowOrderGoods orderGoods = new FlowOrderGoods();
                orderGoods.setCreateTime(new Date());
                orderGoods.setUpdateTime(new Date());
                orderGoods.setGoodsId(gid);
                orderGoods.setGoodsCount(count);
                orderGoods.setGoodsPrice(new BigDecimal(price));
                orderGoods.setGoodsName(a[3]);
                flowOrderGoods.add(orderGoods);
                goodsPrice += price * count;
            }
        }else{
            goodsPrice = 0;
        }

        //查询优惠卷信息
        FlowCoupon flowCoupon = null;
        double couponPrice = 0;
        if(couponId != -1){
            QueryWrapper<FlowCoupon> flowCouponQueryWrapper = new QueryWrapper<>();
            flowCouponQueryWrapper.eq("coupon_id",couponId);
            flowCoupon = flowCouponService.getOne(flowCouponQueryWrapper);
            couponPrice = flowCoupon.getMoneys().doubleValue();
        }
        //创建该类型订单
        FlowOrder flowOrder = new FlowOrder();
        flowOrder.setDyMemberId(this.flowDouyinMember.getMemberId());
        flowOrder.setBegAddress(begComAddress);
        flowOrder.setEndAddress(endComAddress);
        flowOrder.setBegLocation(begLocation);
        flowOrder.setEndLocation(endLocation);
        flowOrder.setOrderType(id);
        flowOrder.setServiceType(serviceType);
        flowOrder.setName(name);
        flowOrder.setPhone(phone);
        flowOrder.setUseDate(date);
        flowOrder.setUpdateTime(new Date());
        flowOrder.setCreateTime(new Date());
        flowOrder.setServiceCity(begCity);
        flowOrder.setNotes(notes);
        flowOrder.setBegElevatorPrice(new BigDecimal(begElevatorPrice));
        flowOrder.setEndElevatorPrice(new BigDecimal(endElevatorPrice));
        flowOrder.setDepositPay(1l);
        //计算订单费用
        flowOrder.setMoneys(new BigDecimal(basePrice));
        flowOrder.setKilometer(new BigDecimal(distance));
        flowOrder.setSettlementMoneys(new BigDecimal(distancePrice));
        flowOrder.setPayMoneys(new BigDecimal(basePrice + distancePrice + goodsPrice + begElevatorPrice + endElevatorPrice));
        BigDecimal AllPayMon=new BigDecimal(basePrice + distancePrice + goodsPrice + begElevatorPrice + endElevatorPrice - couponPrice);
        if(!StringUtils.isEmpty(allPay)){
            flowOrder.setAllPayMoneys(new BigDecimal(allPay));
            BigDecimal res1 = new BigDecimal(allPay).divide(new BigDecimal("10"),2,BigDecimal.ROUND_UP);
            BigDecimal res2 = res1.multiply(new BigDecimal("3"));
            flowOrder.setDeposit(res2);
        }else {
            flowOrder.setAllPayMoneys(new BigDecimal(basePrice + distancePrice + goodsPrice + begElevatorPrice + endElevatorPrice - couponPrice));
            BigDecimal res1 = AllPayMon.divide(new BigDecimal("10"),2,BigDecimal.ROUND_UP);
            BigDecimal res2 = res1.multiply(new BigDecimal("3"));
            flowOrder.setDeposit(res2);
        }

        if(!StringUtils.isEmpty(superUserId)){
            flowOrder.setSuperUserId(Long.valueOf(superUserId));
//            QueryWrapper<FlowWxMember> flowWxMemberQueryWrapper = new QueryWrapper<>();
//            flowWxMemberQueryWrapper.eq("member_id",this.wxMember.getMemberId());
//            FlowWxMember flowWxMember=flowWxMemberService.getOne(flowWxMemberQueryWrapper);
//            flowWxMember.setSuperUserId(Long.valueOf(superUserId));
//            flowWxMemberService.updateById(flowWxMember);
        }

        flowOrder.setKilometerNote(distanceNotes);
        flowOrder.setStoreId(storeId);
        flowOrder.setStoreName(flowStoreCity.getStoreName());
        //订单状态
        flowOrder.setOrderCode(CommonUtil.getRanDomStringId());
        flowOrder.setOrderStatus(OrderStatus.OrderWaitConfirm);
        flowOrder.setIsRefund(OrderStatus.NoRefund);
        flowOrder.setPayStatus(OrderStatus.NoPay);
        flowOrder.setOrderFrom(OrderStatus.fromDY);
        //

        boolean result = flowOrderService.save(flowOrder);
        if(!result){
            return ResponseData.error("预约失败");
        }
        for (int i = 0;i<flowOrderGoods.size();i++){
            flowOrderGoods.get(i).setOrderId(flowOrder.getOrderId());
            flowOrderGoodsService.save(flowOrderGoods.get(i));
        }
        if(flowCoupon != null){
            //更新优惠卷的状态
            flowCoupon.setUseTime(new Date());
            flowCoupon.setIsUsed(1);
            flowCouponService.updateById(flowCoupon);
            //新增订单明细
            FlowOrderDis flowOrderDis = new FlowOrderDis();
            flowOrderDis.setOrderId(flowOrder.getOrderId());
            flowOrderDis.setNote(flowCoupon.getCouponTitle());
            flowOrderDis.setDisMoneys(flowCoupon.getMoneys());
            flowOrderDis.setCouponId(couponId);
            flowOrderDis.setType(0);
            flowOrderDisService.save(flowOrderDis);
        }
        FlowOrderLog flowOrderLog = new FlowOrderLog();
        flowOrderLog.setBegAddress(begAddress);
        flowOrderLog.setBegCity(begCity);
        flowOrderLog.setBegProvince(begProvince);
        flowOrderLog.setBegComAddress(begComAddress);
        flowOrderLog.setBegDetail(begDetail);
        flowOrderLog.setBegElevator(begElevator);
        flowOrderLog.setBegLocation(begLocation);
        flowOrderLog.setBegPoiName(begPoiName);

        flowOrderLog.setEndAddress(endAddress);
        flowOrderLog.setEndCity(endCity);
        flowOrderLog.setEndComAddress(endComAddress);
        flowOrderLog.setEndElevator(endElevator);
        flowOrderLog.setEndDetail(endDetail);
        flowOrderLog.setEndLocation(endLocation);
        flowOrderLog.setEndProvince(endProvince);
        flowOrderLog.setEndPoiName(endPoiName);

        flowOrderLog.setOrderId(flowOrder.getOrderId());

        flowOrderLog.setCreateTime(new Date());
        flowOrderLog.setUpdateTime(new Date());

        flowOrderLogService.save(flowOrderLog);
        this.sendMsg(flowOrder);

        if(!StringUtils.isEmpty(superUserId)){

            QueryWrapper<FlowDouyinMember> flowWxMemberQueryWrapper = new QueryWrapper<>();
            flowWxMemberQueryWrapper.eq("member_id",superUserId);
            FlowDouyinMember flowWxMember= flowDouyinMemberService.getOne(flowWxMemberQueryWrapper);
            WxTemplateUtil wxTemplateUtil=new WxTemplateUtil();
            wxTemplateUtil.send_template_message(flowOrder,flowWxMember.getDouyinOpenid());

        }

//        if(!StringUtils.isEmpty(superUserId)){
//            WxTemplateUtil wxTemplateUtil=new WxTemplateUtil();
//            wxTemplateUtil.send_template_message(flowOrder,flowOrder.getSuperUserId().toString());
//        }
        return ResponseData.success(flowOrder.getOrderId());
    }

    //订单支付
    @RequestMapping("/orderPay")
    @ResponseBody
    public ResponseData orderPay(HttpServletRequest request) throws AlipayApiException {
        HttpBaseRequest baseRequest = new HttpBaseRequest(request);
        long orderId = baseRequest.getLong("orderId");
        if(orderId == -1){
            return ResponseData.error("请选择订单");
        }
        //查询订单的类型

        //查询订单信息
        QueryWrapper<FlowOrder> flowOrderQueryWrapper = new QueryWrapper<>();
        flowOrderQueryWrapper.eq("order_id",orderId);
        flowOrderQueryWrapper.eq("dy_member_id",this.flowDouyinMember.getMemberId());
        FlowOrder flowOrder = flowOrderService.getOne(flowOrderQueryWrapper);
        if(flowOrder == null){
            return ResponseData.error("不存在该订单");
        }
        if(flowOrder.getOrderStatus() != OrderStatus.OrderWaitPay){
            return ResponseData.error("该订单不能支付，请等待客服处理");
        }
        //查询订单类型
        QueryWrapper<FlowService> flowServiceQueryWrapper = new QueryWrapper<>();
        flowServiceQueryWrapper.eq("service_id",flowOrder.getOrderType());
        FlowService flowService = flowServiceService.getOne(flowServiceQueryWrapper);
        String body = "";
        if(flowService != null){
            body = flowService.getServiceName();
        }
        //创建支付
        FlowPayInfo flowPayInfo = new FlowPayInfo();
        flowPayInfo.setOrderId(flowOrder.getOrderId());
        flowPayInfo.setPayStatus(OrderStatus.NoPay);
        flowPayInfo.setIsRefund(OrderStatus.NoRefund);
        flowPayInfo.setCreateTime(new Date());
        flowPayInfo.setMoneys(flowOrder.getAllPayMoneys());
        flowPayInfo.setPayCode(CommonUtil.getRanDomStringId());
        flowPayInfo.setPayType(MEMBER_TYPE_DOUYIN);
        flowPayInfo.setUserId(this.flowDouyinMember.getDouyinOpenid());
        flowPayInfo.setUpdateTime(new Date());
        boolean result = flowPayInfoService.save(flowPayInfo);
        if(result){
            try{
                //发起抖音预支付
                DouyinPrePayRes res = DouyinHttpUtil.prePay(flowOrder,flowPayInfo,"orderPay:"+body);
                if(res.getErr_no()==0){
                    return ResponseData.success(res.getData());
                }else {
                    return ResponseData.error("支付授权生成失败1");
                }

            }catch (Exception e){
                e.printStackTrace();
                return ResponseData.error("支付授权生成失败1");
            }
        }else {
            return ResponseData.error("创建订单失败");
        }
    }

    //订单定金支付
    @RequestMapping("/orderDepositPay")
    @ResponseBody
    public ResponseData orderDepositPay(HttpServletRequest request) throws AlipayApiException {
        HttpBaseRequest baseRequest = new HttpBaseRequest(request);
        long orderId = baseRequest.getLong("orderId");
        if(orderId == -1){
            return ResponseData.error("请选择订单");
        }
        //查询订单的类型

        //查询订单信息
        QueryWrapper<FlowOrder> flowOrderQueryWrapper = new QueryWrapper<>();
        flowOrderQueryWrapper.eq("order_id",orderId);
        flowOrderQueryWrapper.eq("dy_member_id",this.flowDouyinMember.getMemberId());
        FlowOrder flowOrder = flowOrderService.getOne(flowOrderQueryWrapper);
        if(flowOrder == null){
            return ResponseData.error("不存在该订单");
        }
//        if(flowOrder.getOrderStatus() != OrderStatus.OrderWaitPay){
//            return ResponseData.error("该订单不能支付，请等待客服处理");
//        }
        //查询订单类型
        QueryWrapper<FlowService> flowServiceQueryWrapper = new QueryWrapper<>();
        flowServiceQueryWrapper.eq("service_id",flowOrder.getOrderType());
        FlowService flowService = flowServiceService.getOne(flowServiceQueryWrapper);
        String body = "";
        if(flowService != null){
            body = flowService.getServiceName();
        }
        //创建支付
        FlowPayInfo flowPayInfo = new FlowPayInfo();
        flowPayInfo.setOrderId(flowOrder.getOrderId());
        flowPayInfo.setPayStatus(OrderStatus.NoPay);
        flowPayInfo.setIsRefund(OrderStatus.NoRefund);
        flowPayInfo.setCreateTime(new Date());
        flowPayInfo.setMoneys(flowOrder.getDeposit());
        flowPayInfo.setPayCode(CommonUtil.getRanDomStringId());
        flowPayInfo.setPayType(MEMBER_TYPE_DOUYIN);
        flowPayInfo.setUserId(this.flowDouyinMember.getDouyinOpenid());
        flowPayInfo.setUpdateTime(new Date());
        boolean result = flowPayInfoService.save(flowPayInfo);
        if(result){
            try{

                //发起抖音预支付
                DouyinPrePayRes res = DouyinHttpUtil.prePay(flowOrder,flowPayInfo,"定金支付:"+body);
                if(res.getErr_no()==0){
                    return ResponseData.success(res.getData());
                }else {
                    return ResponseData.error("支付授权生成失败1");
                }


            }catch (Exception e){
                e.printStackTrace();
                return ResponseData.error("支付授权生成失败1");
            }
        }else {
            return ResponseData.error("创建订单失败");
        }
    }

    //订单尾款支付
    @RequestMapping("/orderEndPay")
    @ResponseBody
    public ResponseData orderEndPay(HttpServletRequest request) throws AlipayApiException {
        HttpBaseRequest baseRequest = new HttpBaseRequest(request);
        long orderId = baseRequest.getLong("orderId");
        BigDecimal price = new BigDecimal(baseRequest.getString("price"));
        if(orderId == -1){
            return ResponseData.error("请选择订单");
        }
        //查询订单的类型

        //查询订单信息
        QueryWrapper<FlowOrder> flowOrderQueryWrapper = new QueryWrapper<>();
        flowOrderQueryWrapper.eq("order_id",orderId);
        flowOrderQueryWrapper.eq("dy_member_id",this.flowDouyinMember.getMemberId());
        FlowOrder flowOrder = flowOrderService.getOne(flowOrderQueryWrapper);
        if(flowOrder == null){
            return ResponseData.error("不存在该订单");
        }
        if(flowOrder.getOrderStatus() != OrderStatus.OrderWaitPay){
            return ResponseData.error("该订单不能支付，请等待客服处理");
        }
        //查询订单类型
        QueryWrapper<FlowService> flowServiceQueryWrapper = new QueryWrapper<>();
        flowServiceQueryWrapper.eq("service_id",flowOrder.getOrderType());
        FlowService flowService = flowServiceService.getOne(flowServiceQueryWrapper);
        String body = "";
        if(flowService != null){
            body = flowService.getServiceName();
        }
        //创建支付
        FlowPayInfo flowPayInfo = new FlowPayInfo();
        flowPayInfo.setOrderId(flowOrder.getOrderId());
        flowPayInfo.setPayStatus(OrderStatus.NoPay);
        flowPayInfo.setIsRefund(OrderStatus.NoRefund);
        flowPayInfo.setCreateTime(new Date());
        flowPayInfo.setMoneys(price);
        flowPayInfo.setPayCode(CommonUtil.getRanDomStringId());
        flowPayInfo.setPayType(MEMBER_TYPE_DOUYIN);
        flowPayInfo.setUserId(this.flowDouyinMember.getDouyinOpenid());
        flowPayInfo.setUpdateTime(new Date());
        boolean result = flowPayInfoService.save(flowPayInfo);
        if(result){
            try{

                //发起抖音预支付
                DouyinPrePayRes res = DouyinHttpUtil.prePay(flowOrder,flowPayInfo,"尾款支付:"+body);
                if(res.getErr_no()==0){
                    return ResponseData.success(res.getData());
                }else {
                    return ResponseData.error("支付授权生成失败1");
                }

            }catch (Exception e){
                e.printStackTrace();
                return ResponseData.error("支付授权生成失败1");
            }
        }else {
            return ResponseData.error("创建订单失败");
        }
    }

    //订单评价
    @RequestMapping("/orderComment")
    @ResponseBody
    public ResponseData orderComment(HttpServletRequest request){
        HttpBaseRequest baseRequest = new HttpBaseRequest(request);
        String detail = baseRequest.getString("detail");
        String imgs = baseRequest.getString("imgs");
        long orderId = baseRequest.getLong("orderId");
        double start = baseRequest.getDouble("start",0);
        String tag = baseRequest.getString("tag");
        if(orderId == -1){
            return ResponseData.error("请选择评论订单");
        }
        if(detail.equals("")){
            return ResponseData.error("请输入评论内容");
        }
        QueryWrapper<FlowOrder> flowOrderQueryWrapper = new QueryWrapper<>();
        flowOrderQueryWrapper.eq("order_id",orderId);

        FlowOrder flowOrder = flowOrderService.getOne(flowOrderQueryWrapper);
        if(flowOrder == null){
            return ResponseData.error("不存在该订单");
        }
        //查询服务类型
        QueryWrapper<FlowService> flowServiceQueryWrapper = new QueryWrapper<>();
        flowServiceQueryWrapper.eq("service_id",flowOrder.getOrderType());
        FlowService flowService = flowServiceService.getOne(flowServiceQueryWrapper);
        String serviceName = "";
        if(flowService != null){
            serviceName = flowService.getServiceName();
        }
        int update = flowOrderService.updateOrderStatus(orderId,OrderStatus.OrderCompletion,OrderStatus.OrderServiceSuccess);
        if(update > 0){
            FlowMemberComment flowMemberComment = new FlowMemberComment();
            flowMemberComment.setMemberPhone(flowOrder.getPhone());
            flowMemberComment.setMemberName(flowOrder.getName());
            flowMemberComment.setImgUrls(imgs);
            flowMemberComment.setCity(flowOrder.getServiceCity());
            flowMemberComment.setNote(detail);
            flowMemberComment.setStart(new BigDecimal(start));
            flowMemberComment.setOrderType(flowOrder.getOrderType());
            flowMemberComment.setTypeName(serviceName);
            flowMemberComment.setTag(tag);
            boolean result = flowMemberCommentService.save(flowMemberComment);
            if(result){
                return ResponseData.success("评论成功");
            }else {
                return ResponseData.error("评论失败");
            }
        }else {
            return ResponseData.error("评论失败");
        }
    }

    //上传图片
    @ResponseBody
    @RequestMapping("/uploadImg")
    public ResponseData uploadImg(HttpServletRequest request,@RequestPart("file") MultipartFile file){
        UploadResult uploadResult = this.fileInfoService.uploadFile(file);
        return ResponseData.success(0, "上传成功", "/upload/"+uploadResult.getFinalName());
    }

    //用户申请退款审核
    @ResponseBody
    @RequestMapping("/refundOrder")
    public ResponseData refundOrder(FlowOrderParam flowOrderParam){
        FlowOrder detail = this.flowOrderService.getById(flowOrderParam.getOrderId());
        if(StringUtils.isEmpty(detail.getPayCode())&&StringUtils.isEmpty(detail.getDepositPayCode())){
            return ResponseData.error("订单未支付");
        }
        //int result = this.flowOrderService.updateOrderStatus(detail.getOrderId(),OrderStatus.OrderDealing,OrderStatus.OrderWaitConfirm);
        FlowOrderParam flowOrderParam2 = new FlowOrderParam();
        flowOrderParam2.setRefundStatus(flowOrderParam.getRefundStatus());
        flowOrderParam2.setOrderId(flowOrderParam.getOrderId());
        flowOrderService.update(flowOrderParam2);
        if(flowOrderParam.getRefundStatus() ==1){
            //更新订单的操作人员
//            FlowOrderParam flowOrderParam1 = new FlowOrderParam();
//            LoginUser user = LoginContextHolder.getContext().getUser();
//            flowOrderParam1.setUpdateUser(user.getId());
//            flowOrderParam1.setOrderId(flowOrderParam.getOrderId());
//            flowOrderService.update(flowOrderParam1);
            //申请退款
            try{
                QueryWrapper<FlowService> flowServiceQueryWrapper = new QueryWrapper<>();
                flowServiceQueryWrapper.eq("service_id",detail.getOrderType());
                FlowService flowService = flowServiceService.getOne(flowServiceQueryWrapper);
                //发送支付成功短信
                //发送到注册手机号
                QueryWrapper<FlowDouyinMember> flowWxMemberQueryWrapper = new QueryWrapper<>();
                flowWxMemberQueryWrapper.eq("member_id",detail.getDyMemberId());
                flowWxMemberQueryWrapper.last("limit 1");
                FlowDouyinMember flowWxMember = flowDouyinMemberService.getOne(flowWxMemberQueryWrapper);


                if(detail.getZfbMemberId() != null && detail.getZfbMemberId() > 0){
//                    QueryWrapper<FlowZfbMember> flowZfbMemberQueryWrapper = new QueryWrapper<>();
//                    flowZfbMemberQueryWrapper.eq("member_id",detail.getZfbMemberId());
//                    flowZfbMemberQueryWrapper.last("limit 1");
//                    FlowZfbMember flowZfbMember = flowZfbMemberService.getOne(flowZfbMemberQueryWrapper);
//                    if(flowZfbMember != null){
//                        AliyuncsUtil.sendSmsOrder(3,flowZfbMember.getAccount(),flowService.getServiceName());
//                    }

                    this.sendRefundMsg(detail,flowWxMember);
                }else if(detail.getBdMemberId() != null && detail.getBdMemberId() > 0){
//                    QueryWrapper<FlowBdMember> flowBdMemberQueryWrapper = new QueryWrapper<>();
//                    flowBdMemberQueryWrapper.eq("member_id",detail.getBdMemberId());
//                    flowBdMemberQueryWrapper.last("limit 1");
//                    FlowBdMember flowBdMember = flowBdMemberService.getOne(flowBdMemberQueryWrapper);
//                    if(flowBdMember != null){
//                        AliyuncsUtil.sendSmsOrder(3,flowBdMember.getAccount(),flowService.getServiceName());
//                    }
                    this.sendRefundMsg(detail,flowWxMember);

                }else if(detail.getWxMemberId() != null && detail.getWxMemberId() > 0){
//                    QueryWrapper<FlowWxMember> flowWxMemberQueryWrapper = new QueryWrapper<>();
//                    flowWxMemberQueryWrapper.eq("member_id",detail.getWxMemberId());
//                    flowWxMemberQueryWrapper.last("limit 1");
//                    FlowWxMember flowWxMember = flowWxMemberService.getOne(flowWxMemberQueryWrapper);
//                    if(flowWxMember != null){
//                        AliyuncsUtil.sendSms(3,flowWxMember.getAccount(),flowService.getServiceName());
//                    }
                    this.sendRefundMsg(detail,flowWxMember);

                }else if(detail.getWxMemberId() != null && detail.getDyMemberId() > 0){
//                    QueryWrapper<FlowWxMember> flowWxMemberQueryWrapper = new QueryWrapper<>();
//                    flowWxMemberQueryWrapper.eq("member_id",detail.getWxMemberId());
//                    flowWxMemberQueryWrapper.last("limit 1");
//                    FlowWxMember flowWxMember = flowWxMemberService.getOne(flowWxMemberQueryWrapper);
//                    if(flowWxMember != null){
//                        AliyuncsUtil.sendSms(3,flowWxMember.getAccount(),flowService.getServiceName());
//                    }
                    this.sendRefundMsg(detail,flowWxMember);

                }
            }catch (Exception e){
                e.printStackTrace();
            }
            return ResponseData.success("操作成功");
        }
        else {
            return ResponseData.error("操作失败");
        }

    }

    /**
     * 根据订单查询发送的短信
     * @param flowOrder
     */
    public void sendRefundMsg(FlowOrder flowOrder,FlowDouyinMember flowWxMember){
        System.out.println("发送申请退款通知："+flowOrder.getName()+":"+flowOrder.getPhone());
        String name="";
        if(StringUtils.isEmpty(flowWxMember.getNickName())){
            name="xxx";
        }else {
            name=flowWxMember.getNickName();
        }
        //查询服务的网点
        try{
            if(flowOrder.getStoreId() == null || flowOrder.getStoreId().intValue() <= 0){
                //查询总公司网点
                QueryWrapper<Dept> deptQueryWrapper = new QueryWrapper<>();
                deptQueryWrapper.eq("pid",0);
                deptQueryWrapper.last("limit 1");
                Dept dept = deptService.getOne(deptQueryWrapper);
                if(dept != null){
                    //查询该客服人员
                    QueryWrapper<FlowDeptPhones> flowDeptPhonesQueryWrapper = new QueryWrapper<>();
                    flowDeptPhonesQueryWrapper.eq("dept_id",dept.getDeptId());
                    List<FlowDeptPhones> flowDeptPhones = flowDeptPhonesService.list(flowDeptPhonesQueryWrapper);
                    if(flowDeptPhones.size() > 0){
                        Random random = new Random();
                        int n = random.nextInt(flowDeptPhones.size());
                        AliyuncsUtil.sendSms(6,flowDeptPhones.get(n).getMobile(),name,flowWxMember.getAccount());
                    }

                }
            }else{
                //查询管理网点的客服电话
                QueryWrapper<FlowDeptPhones> flowDeptPhonesQueryWrapper = new QueryWrapper<>();
                flowDeptPhonesQueryWrapper.apply("dept_id in (select dept_id from flow_dept_store where store_id = "+flowOrder.getStoreId().longValue()+")");
                List<FlowDeptPhones> flowDeptPhones = flowDeptPhonesService.list(flowDeptPhonesQueryWrapper);
                if(flowDeptPhones.size() > 0){
                    Random random = new Random();
                    int n = random.nextInt(flowDeptPhones.size());
                    AliyuncsUtil.sendSms(6,flowDeptPhones.get(n).getMobile(),name,flowWxMember.getAccount());
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    //假订单评价
    @RequestMapping("/falseOrderComment")
    @ResponseBody
    public ResponseData falseOrderComment(HttpServletRequest request){
        HttpBaseRequest baseRequest = new HttpBaseRequest(request);
        String detail = baseRequest.getString("detail");
        String imgs = baseRequest.getString("imgs");
        String phone = baseRequest.getString("phone");
        double start = baseRequest.getDouble("start",0);
        String tag = baseRequest.getString("tag");

        if(detail.equals("")){
            return ResponseData.error("请输入评论内容");
        }




        FlowMemberComment flowMemberComment = new FlowMemberComment();
        flowMemberComment.setMemberPhone(phone);
        flowMemberComment.setMemberName("xxx");
        flowMemberComment.setImgUrls(imgs);
        flowMemberComment.setCity("武汉");
        flowMemberComment.setNote(detail);
        flowMemberComment.setStart(new BigDecimal(start));
        flowMemberComment.setOrderType(1l);
        flowMemberComment.setTypeName("同城搬家");
        flowMemberComment.setTag(tag);
        boolean result = flowMemberCommentService.save(flowMemberComment);
        if(result){
            return ResponseData.success("评论成功");
        }else {
            return ResponseData.error("评论失败");
        }

    }

    //获取二维码
    @RequestMapping("/getQrCode")
    @ResponseBody
    public ResponseData getQrCode(HttpServletRequest request){
        HttpBaseRequest baseRequest = new HttpBaseRequest(request);
        String parm = baseRequest.getString("parm");
        String memberId = baseRequest.getString("memberId");

        String token= WeiXinUtil.getToken();
        String path=this.getClass().getResource("/").getPath()+"uploadFiles/QrCode/"+"Code"+memberId+".png";
//        String path="Code"+memberId;
        System.out.println("SSSSSSSSSSSSSSS"+path);
        String bytes=WeiXinUtil.getQrCode(token,parm,path);
        return ResponseData.success(bytes);
    }

    @RequestMapping("/submitUserInfo")
    @ResponseBody
    public ResponseData submitUserInfo(HttpServletRequest request) {
        HttpBaseRequest baseRequest = new HttpBaseRequest(request);
        long memberId = baseRequest.getLong("id");

        QueryWrapper<FlowDouyinMember> flowWxMemberQueryWrapper = new QueryWrapper<>();
        flowWxMemberQueryWrapper.eq("member_id",memberId);
        FlowDouyinMember flowWxMember= flowDouyinMemberService.getOne(flowWxMemberQueryWrapper);
        if(flowWxMember==null){
            return ResponseData.error("用户未登录");
        }

        String name = baseRequest.getString("name");
        String province = baseRequest.getString("province");
        String city = baseRequest.getString("city");
        String district = baseRequest.getString("district");
//        String township = baseRequest.getString("township");
        String region = baseRequest.getString("region");
        String remaks = baseRequest.getString("remaks");

        flowWxMember.setNickName(name);
        flowWxMember.setProvince(province);
        flowWxMember.setCity(city);
        flowWxMember.setDistrict(district);
        flowWxMember.setRegion(region);
        flowWxMember.setRemaks(remaks);
        flowWxMember.setOneAuthority("0");

        flowDouyinMemberService.updateById(flowWxMember);
        return ResponseData.success();
    }


    //订单列表
    @RequestMapping("/extensionOrderList")
    @ResponseBody
    public ResponseData extensionOrderList(HttpServletRequest request){
        HttpBaseRequest baseRequest = new HttpBaseRequest(request);
        int pagesize = baseRequest.getInt("pagesize",10);
        int cpage = baseRequest.getInt("cpage",1);
        long type = baseRequest.getLong("type");

        QueryWrapper<FlowOrder> flowOrderQueryWrapper = new QueryWrapper<>();
        flowOrderQueryWrapper.eq("super_user_id",this.flowDouyinMember.getMemberId());
        if(type == 0){
            flowOrderQueryWrapper.apply("(order_status != "+OrderStatus.OrderCansel+" and order_status != "+OrderStatus.OrderServiceSuccess+" and order_status != "+OrderStatus.OrderCompletion+")");
        }else if(type == 1){
            flowOrderQueryWrapper.apply("(order_status = "+OrderStatus.OrderServiceSuccess+" or order_status = "+OrderStatus.OrderCompletion+")");
        }else {
            flowOrderQueryWrapper.eq("order_status",OrderStatus.OrderCansel);
        }

        flowOrderQueryWrapper.orderByDesc("create_time");

        IPage page = new Page<FlowOrder>(cpage,pagesize);
        page = flowOrderService.getBaseMapper().selectPage(page,flowOrderQueryWrapper);
        List<FlowOrder> flowOrders = page.getRecords();
        if(flowOrders.size() != 0){
            List<Long> ids = new ArrayList<>();
            for (int i = 0;i < flowOrders.size();i++){
                ids.add(flowOrders.get(i).getOrderType());
                flowOrders.get(i).setOrderStatusStr(flowOrderService.orderStatus(flowOrders.get(i).getOrderStatus()));
            }
            //查询订单的服务类型
            QueryWrapper<FlowService> flowServiceQueryWrapper = new QueryWrapper<>();
            flowServiceQueryWrapper.in("service_id",ids);
            List<FlowService> flowService = flowServiceService.list(flowServiceQueryWrapper);
            for (int i = 0;i < flowOrders.size();i++){
                for (int j = 0;j<flowService.size();j++){
                    if(flowOrders.get(i).getOrderType().longValue() == flowService.get(j).getServiceId().longValue()){
                        flowOrders.get(i).setOrderTypeName(flowService.get(j).getServiceName());
                        break;
                    }
                }
            }
        }

        return ResponseData.success(flowOrders);
    }

    /**
     * 佣金汇总
     * @param flowCommissionManagementParam
     * @return
     */
    @ResponseBody
    @RequestMapping("/getOnly")
    public FlowCommissionManagement getOnly(FlowCommissionManagementParam flowCommissionManagementParam) {
        QueryWrapper<FlowCommissionManagement> flowCommissionManagementQueryWrapper = new QueryWrapper<>();
        flowCommissionManagementQueryWrapper.eq("user_id",flowCommissionManagementParam.getUserId());
        flowCommissionManagementQueryWrapper.eq("only_sign",1l);
        flowCommissionManagementQueryWrapper.last("limit 1");
        FlowCommissionManagement flowCommissionManagement=flowCommissionManagementService.getOne(flowCommissionManagementQueryWrapper);

        QueryWrapper<FlowCommissionManagement> flowCommissionManagementQueryWrapper1 = new QueryWrapper<>();
        flowCommissionManagementQueryWrapper1.eq("user_id",flowCommissionManagementParam.getUserId());
        flowCommissionManagementQueryWrapper1.eq("only_sign",3l);
        List<FlowCommissionManagement> flowCommissionManagementList=flowCommissionManagementService.list(flowCommissionManagementQueryWrapper1);

        for (FlowCommissionManagement f:flowCommissionManagementList){
            if(StringUtils.isEmpty(f.getDrawSign())||f.getDrawSign()!=1){
                flowCommissionManagement.setApplyDrawPrice(f.getApplyDrawPrice());
            }
        }

        return flowCommissionManagement;
    }

    /**
     * 获取每笔订单佣金记录
     * @param flowCommissionManagementParam
     * @return
     */
    @ResponseBody
    @RequestMapping("/getFlowCommissionManagementList")
    public List<FlowCommissionManagement> getFlowCommissionManagementList(FlowCommissionManagementParam flowCommissionManagementParam) {
        QueryWrapper<FlowCommissionManagement> flowCommissionManagementQueryWrapper = new QueryWrapper<>();
        flowCommissionManagementQueryWrapper.eq("user_id",flowCommissionManagementParam.getUserId());
        flowCommissionManagementQueryWrapper.eq("only_sign",0l);
        flowCommissionManagementQueryWrapper.last("limit 1");
        List<FlowCommissionManagement> list=flowCommissionManagementService.list(flowCommissionManagementQueryWrapper);
        return list;
    }

    /**
     * 提现申请记录
     * @param flowCommissionManagementParam
     * @return
     */
    @ResponseBody
    @RequestMapping("/getApplyDraw")
    public List<FlowCommissionManagement> getApplyDraw(FlowCommissionManagementParam flowCommissionManagementParam) {
        QueryWrapper<FlowCommissionManagement> flowCommissionManagementQueryWrapper = new QueryWrapper<>();
        flowCommissionManagementQueryWrapper.eq("user_id",flowCommissionManagementParam.getUserId());
        flowCommissionManagementQueryWrapper.eq("only_sign",2l);
        flowCommissionManagementQueryWrapper.last("limit 1");
        List<FlowCommissionManagement> list=flowCommissionManagementService.list(flowCommissionManagementQueryWrapper);
        return list;
    }

    @RequestMapping("/UserDetail")
    @ResponseBody
    public ResponseData UserDetail(HttpServletRequest request) {
        HttpBaseRequest baseRequest = new HttpBaseRequest(request);
        long memberId = baseRequest.getLong("id");
        FlowDouyinMember detail = this.flowDouyinMemberService.getById(memberId);
        return ResponseData.success(detail);
    }

    @RequestMapping("/withdrawal")
    @ResponseBody
    public ResponseData withdrawal(HttpServletRequest request) {
        HttpBaseRequest baseRequest = new HttpBaseRequest(request);
        String memberId = baseRequest.getString("id");
        String price = baseRequest.getString("price");
        String account = baseRequest.getString("account");
        QueryWrapper<FlowCommissionManagement> flowCommissionManagementQueryWrapper1 = new QueryWrapper<>();
        flowCommissionManagementQueryWrapper1.eq("user_id",memberId);
        flowCommissionManagementQueryWrapper1.eq("only_sign",3l);
        List<FlowCommissionManagement> flowCommissionManagementList=flowCommissionManagementService.list(flowCommissionManagementQueryWrapper1);

        for (FlowCommissionManagement f:flowCommissionManagementList){


            if(StringUtils.isEmpty(f.getDrawSign())||f.getDrawSign()!=1){

                return ResponseData.error("有未审核的提现订单");
            }
        }
        FlowCommissionManagement flowCommissionManagement=new FlowCommissionManagement();
        flowCommissionManagement.setUserId(memberId);
        flowCommissionManagement.setOnlySign(3l);
        flowCommissionManagement.setDrawSign(0l);
        flowCommissionManagement.setAccount(account);
        flowCommissionManagement.setApplyDrawPrice(new BigDecimal(price));
        flowCommissionManagementService.save(flowCommissionManagement);

        QueryWrapper<FlowCommissionManagement> flowCommissionManagementQueryWrapper = new QueryWrapper<>();
        flowCommissionManagementQueryWrapper.eq("user_id",memberId);
        flowCommissionManagementQueryWrapper.eq("only_sign",1l);
        FlowCommissionManagement flowCommissionManagementOne=flowCommissionManagementService.getOne(flowCommissionManagementQueryWrapper);


        BigDecimal res=flowCommissionManagementOne.getCanDrawPrice().subtract(new BigDecimal(price));
        flowCommissionManagementOne.setCanDrawPrice(res);
        flowCommissionManagementService.updateById(flowCommissionManagementOne);
        return ResponseData.success("");
    }


    /**
     * 回调用已支付
     *
     * @param payCode           支付代码
     * @param thirdPartyPayCode 第三方支付代码
     */
    private void callbackPayed(String payCode,String thirdPartyPayCode){

        //此处做自己的业务处理
        //查询订单
        QueryWrapper<FlowPayInfo> flowPayInfoQueryWrapper = new QueryWrapper<>();
        flowPayInfoQueryWrapper.eq("pay_code",payCode);
        flowPayInfoQueryWrapper.last("limit 1");
        FlowPayInfo flowPayInfo = flowPayInfoService.getOne(flowPayInfoQueryWrapper);
        if(flowPayInfo != null){
            flowPayInfo.setTradeNo(thirdPartyPayCode);
            flowPayInfo.setUpdateTime(new Date());
            flowPayInfo.setPayTime(new Date());
            flowPayInfo.setPayStatus(OrderStatus.IsPay);
            flowPayInfoService.updateById(flowPayInfo);
            //更新订单
            QueryWrapper<FlowOrder> flowOrderQueryWrapper = new QueryWrapper<>();
            flowOrderQueryWrapper.eq("order_id",flowPayInfo.getOrderId());
            flowOrderQueryWrapper.last("limit 1");
            FlowOrder flowOrder = flowOrderService.getOne(flowOrderQueryWrapper);
            if(flowOrder != null) {
                if (flowOrder.isDepositPay() == 1) {
                    flowOrder.setDepositPayCode(payCode);
                    flowOrder.setDepositPay(0l);
                    flowOrderService.updateById(flowOrder);
                } else {
                    flowOrder.setOrderStatus(OrderStatus.OrderWaitService);
                    flowOrder.setPayStatus(OrderStatus.IsPay);
                    flowOrder.setPayCode(payCode);
                    flowOrderService.updateById(flowOrder);
                }

            }
        }


    }
}
